<template>
  <div class="Profile-container">
    <slot name="title">
      <div class="profile-title">{{ title }}</div>
    </slot>
    <slot name="toolbar">
      <div class="toolbar">
        <v-icon @click="openSave" class="icon pointer">
          mdi-content-save
        </v-icon>
      </div>
    </slot>
    <v-card class="profile-content mx-auto elevation-0 d-flex flex-column">
      <v-list-item three-line class="list pl-9 flex-grow-0 flex-shrink-0">
        <v-list-item-avatar
          class="avatar mr-10"
          :class="{ shock: shock }"
          size="104"
          :color="propData.avatar ? '' : 'grey'"
        >
          <v-avatar
            @click="openFileInput"
            class="pointer"
            height="100%"
            width="100%"
          >
            <img
              v-if="propData.avatar"
              :src="propData.avatar"
              :alt="propData.avatar"
            />
          </v-avatar>
          <v-file-input
            v-show="false"
            ref="fileInput"
            @change="uploadAvatar"
            accept="image/*"
          ></v-file-input>
          <v-icon class="avatar-decorate"> mdi-image-area </v-icon>
        </v-list-item-avatar>
        <v-list-item-content class="justify-center">
          <v-list-item-title>
            <div class="name-text mb-2 text-left">
              {{ propData.userName === "" ? "Name" : propData.userName }}
            </div>
            <div class="email-text text-left">
              {{ propData.email === "" ? "Email" : propData.email }}
            </div>
          </v-list-item-title>
        </v-list-item-content>
      </v-list-item>
      <v-form class="form flex-grow-1 d-flex flex-column">
        <v-row
          no-gutters
          class="pt-2 pr-16 pd-7 pl-4 flex-grow-0 flex-shrink-0"
        >
          <v-col
            cols="6"
            :key="userInfo.label"
            v-for="userInfo in userInfoList"
            class="d-flex line"
          >
            <v-col cols="4">
              <v-subheader class="label">
                {{ userInfo.label }}
              </v-subheader>
            </v-col>
            <v-col cols="8" class="text-left input-wrap">
              <v-text-field
                v-if="userInfo.type === 'input'"
                v-model="propData[userInfo.value]"
                v-bind="userInfo"
                v-validate="userInfo.rule"
                :name="userInfo.value"
                :type="userInfo.value === 'password' ? 'password' : 'input'"
                label=""
                class="elevation-0 gray-input"
                solo
                hide-details
              ></v-text-field>
              <v-select
                v-if="userInfo.type === 'select'"
                v-model="propData[userInfo.value]"
                v-bind="userInfo"
                v-validate="userInfo.rule"
                :name="userInfo.value"
                :items="userInfo.items"
                label=""
                class="elevation-0 gray-input"
                solo
                hide-details
              >
              </v-select>
              <span class="vee-validate-error">{{
                errors.first(userInfo.value)
              }}</span>
            </v-col>
          </v-col>
        </v-row>
        <div class="checkbox-group d-flex px-9 pr-16 pb-8" no-gutters>
          <div
            v-for="(checkbox, index) in checkboxGroup"
            :key="checkbox.label"
            class="d-flex justify-end px-3 align-center"
          >
            <span
              class="checkbox-label mr-2"
              :class="{ 'text-left': index === 0 }"
            >
              {{ checkbox.label }}
            </span>
            <v-checkbox
              v-model="propData.right"
              :value="checkbox.value"
              class="pa-0"
              color="orange"
              on-icon="mdi-checkbox-outline"
              hide-details
            >
            </v-checkbox>
          </div>
          <div class="d-flex justify-end align-center">
            <span class="checkbox-label mr-2"> Colour </span>
            <v-checkbox
              v-model="isSelectedColour"
              class="pa-0"
              color="orange"
              on-icon="mdi-checkbox-outline"
              hide-details
            >
            </v-checkbox>
            <v-menu :close-on-content-click="false" offset-y>
              <template v-slot:activator="{ on, attrs }">
                <v-icon v-bind="attrs" v-on="on" class="pointer" small>
                  mdi-chevron-down
                </v-icon>
              </template>
              <input @change="changeColour" type="color" />
            </v-menu>
          </div>
        </div>
        <v-container fluid no-gutters class="mt-2 pa-0 text-left flex-grow-1">
          <v-col class="pa-0">
            <v-btn-toggle
              v-model="selectedNavIndex"
              borderless
              active-class="active-btn"
              class="button-group"
              shaped
              mandatory
            >
              <v-btn class="pl-7 col-5"> User Group </v-btn>
              <v-btn class="col-5"> Location code </v-btn>
            </v-btn-toggle>
          </v-col>
          <v-col
            v-show="selectedNavIndex === 0"
            class="checkbox-group-card pa-0"
          >
            <v-checkbox
              v-model="propData.userGroup"
              v-for="user in userGroup"
              :key="user.id"
              on-icon="mdi-checkbox-outline"
              hide-details
              :label="user.label"
              :value="user.value"
            ></v-checkbox>
          </v-col>
          <v-col class="pa-0 locationCode-wrap" v-show="selectedNavIndex === 1">
            <v-row class="mt-0" no-gutters align="start">
              <v-col class="pl-0 pt-0" :cols="5">
                <v-data-table
                  class="elevation-0 contact-table"
                  :headers="contactHeaders"
                  :items="contactItems"
                  disable-sort
                  hide-default-footer
                >
                  <template #[`item.number`]="{ item }">
                    <div class="d-flex align-center">
                      <v-checkbox
                        v-model="propData.locationCode.contact"
                        class="mt-0 pa-0"
                        hide-details
                        :label="item.number"
                        :value="item.id"
                      ></v-checkbox>
                    </div>
                  </template>
                </v-data-table>
              </v-col>
              <v-col :cols="7">
                <v-data-table
                  class="elevation-0 location-table"
                  hide-default-footer
                  :headers="locationHeaders"
                  :items="locationItems"
                  disable-sort
                >
                  <template #[`item.code`]="{ item }">
                    <div class="d-flex align-center">
                      <v-checkbox
                        v-model="propData.locationCode.location"
                        class="mt-0 pa-0"
                        hide-details
                        :label="item.code"
                        :value="item.id"
                      ></v-checkbox>
                    </div>
                  </template>
                </v-data-table>
              </v-col>
            </v-row>
          </v-col>
        </v-container>
      </v-form>
    </v-card>
    <Dialog
      v-model="showDialog"
      :title="dialogTitle"
      :show-save="false"
      width="480"
    >
      <SaveUser
        @submit="submit"
        :type="isEdit ? 2 : 1"
        :item="propData"
      ></SaveUser>
    </Dialog>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Watch } from "vue-property-decorator";
import EditableText from "@/components/Maintenance/EditableText/EditableText.vue";
import Dialog from "@/components/Maintenance/Dialog/Dialog.vue";
import SaveUser from "@/components/Maintenance/Admin/User/SaveUser.vue";
import { IMemberForm, IMember } from "@/components/Maintenance/index";
import { readerFile } from "@/common/constants/Utils";
import VFileInput from "vuetify/src/components/VFileInput";
type VFileInputInstance = InstanceType<typeof VFileInput>;
interface IAddProfile extends IMemberForm {
  [key: string]: any;
}

interface IEditProfile extends IMember {
  [key: string]: any;
}

interface iUserInfoObj {
  label: string;
  type: string;
  placeholder: string;
  value: string;
  rule?: object | string;
  items?: Array<string>;
}

interface ICheckbox {
  value: string;
  label: string;
}

@Component({
  components: {
    EditableText,
    Dialog,
    SaveUser,
  },
  props: {
    data: {
      type: Object,
      default: () => ({}),
    },
  },
})
export default class Profile extends Vue {
  // dialog
  showDialog = false;
  dialogTitle = "";
  openDialog() {
    this.showDialog = true;
  }
  closeDialog() {
    this.showDialog = false;
  }

  async openSave() {
    const valid: boolean = await this.$validator.validateAll();
    if (!this.propData.avatar) {
      this.shock = true;
      setTimeout(() => {
        this.shock = false;
      }, 200);
    }
    if (valid && this.propData.avatar) {
      this.dialogTitle = "save";
      this.openDialog();
    }
  }

  selectedNavIndex = 0;
  avatar = "";
  get title() {
    if (this.isEdit) {
      return `Profile - ${this.propData.userName}`;
    } else {
      return "New Profile";
    }
  }

  get isEdit() {
    const propData = this.$props.data;
    if (propData && propData.userId !== undefined) {
      return true;
    }
    return false;
  }

  get propData() {
    const propData = this.$props.data;
    if (this.isEdit) {
      // 取消编辑时对列表数据因为引用值而发生的改变
      this.$set(this, "profileData", JSON.parse(JSON.stringify(propData)));
      return this.profileData as IEditProfile;
    } else {
      return this.profileData as IAddProfile;
    }
  }
  @Watch("propData")
  onPropDataChange() {
    this.$validator.reset();
  }

  // upload avatar
  openFileInput() {
    (this.$refs.fileInput as VFileInputInstance).$refs.input.click();
  }
  async uploadAvatar(file: File) {
    const reader: FileReader = await readerFile(file);
    if (!reader.error) {
      console.log(reader);
      this.propData.avatar = reader.result as string;
    } else {
      this.SweetAlertService.error("File upload failed");
    }
  }

  profileData: IEditProfile | IAddProfile = this.getProfileData();

  getProfileData(): IAddProfile {
    return {
      id: "",
      userId: "",
      userName: "",
      avatar: "",
      email: "",
      team: "",
      department: "",
      password: "",
      tel: "",
      language: "",
      head: "",
      status: "",
      colour: "",
      right: [],
      userGroup: [],
      locationCode: {
        contact: [],
        location: [],
      },
    };
  }

  get isSelectedColour() {
    return !!this.propData.colour;
  }

  set isSelectedColour(val: boolean) {
    if (!val) {
      this.propData.colour = "";
    }
  }

  changeColour(e: Event) {
    if (e.target) {
      this.propData.colour = (e.target as HTMLInputElement).value;
    }
  }

  resetProfileData() {
    this.profileData = this.getProfileData();
  }

  contactHeaders = [
    {
      text: "Contact number",
      value: "number",
    },
    {
      text: "Contact Name",
      value: "name",
    },
  ];

  contactItems = [
    {
      id: "1",
      number: "000092",
      name: "Auto Company",
    },
    {
      id: "2",
      number: "000095",
      name: "FIDELITY",
    },
  ];

  locationHeaders = [
    {
      text: "Location code",
      value: "code",
    },
    {
      text: "Location",
      value: "location",
    },
  ];

  locationItems = [
    {
      id: "1",
      code: "AT",
      location: "Auto Office",
    },
  ];

  userGroup = [
    {
      id: "1",
      label: "Admin",
      value: "Admin",
    },
    {
      id: "2",
      label: "Customer Service Team",
      value: "Customer Service Team",
    },
    {
      id: "3",
      label: "Field Service Engineer",
      value: "Field Service Engineer",
    },
    {
      id: "4",
      label: "Group 11",
      value: "Group 11",
    },
    {
      id: "5",
      label: "Group 7",
      value: "Group 7",
    },
    {
      id: "6",
      label: "Project Team",
      value: "Project Team",
    },
  ];

  userInfoList: Array<iUserInfoObj> = [
    {
      label: "User ID",
      value: "userId",
      type: "input",
      placeholder: "please type user ID",
      rule: { required: true },
    },
    {
      label: "Team",
      value: "team",
      type: "select",
      items: ["Team 1", "Team 2", "Team 3"],
      placeholder: "please select Team",
      rule: { required: true },
    },
    {
      label: "User Name",
      value: "userName",
      type: "input",
      placeholder: "please type user Name",
      rule: { required: true },
    },
    {
      label: "Department",
      value: "department",
      type: "select",
      items: ["CS", "ADM", "FSE"],
      placeholder: "please select Department",
      rule: { required: true },
    },
    {
      label: "Password",
      value: "password",
      type: "input",
      placeholder: "please enter password",
      rule: { required: true },
    },
    {
      label: "Email",
      value: "email",
      type: "input",
      placeholder: "please enter email",
      rule: "required|email",
    },
    {
      label: "Language",
      value: "language",
      type: "select",
      items: ["English", "简体中文", "繁体中文"],
      placeholder: "please select Language",
      rule: { required: true },
    },
    {
      label: "Tel",
      value: "tel",
      type: "input",
      placeholder: "please type tel",
      rule: "required|phone",
    },
    {
      label: "Head",
      value: "head",
      type: "select",
      items: ["Amy Chan"],
      placeholder: "please select Head",
      rule: { required: true },
    },
    {
      label: "Status",
      value: "status",
      type: "select",
      items: ["Active", "Suspended", "Resigned"],
      placeholder: "please select Status",
      rule: { required: true },
    },
  ];

  checkboxGroup: Array<ICheckbox> = [
    {
      label: "View all information",
      value: "View all information",
    },
    {
      label: "Announcement",
      value: "Announcement",
    },
    {
      label: "Edit all reocrd",
      value: "Edit all reocrd",
    },
  ];
  // 头像的动画提示是否显示
  shock = false;
  async submit() {
    this.closeDialog();
    this.$emit(this.isEdit ? "edit" : "add", this.propData);
  }
}
</script>

<style lang="scss" scoped>
@import "./Profile.scss";
</style>
